<template>
  <view :id="id" class="mxp-subsection" :style="[subsectionStyle, tabsStyle, cusStyle]">
    <!-- 下划线 -->
    <view class="button-view" :style="{ bottom: lineBottom, transform: `translateX(${data.lineTranslateX}px)`, height, width: `${data.itemWidth}px` }">
      <view
        class="button"
        :style="[{ width: buttonWidth, height: buttonHeight, background: themeColor, borderRadius: props.mode === 'button' ? '4px' : '0px' }, activeStyle]"
      ></view>
    </view>
    <view class="subsection-view">
      <view v-for="(item, index) in newList" :key="index" :style="{ height, width: `${data.itemWidth}px` }" style="display: flex; flex-direction: row">
        <view class="subsection-item" :style="[{ height, flexDirection: iconDirection === 'column' ? 'column' : 'row' }]" @click="setCurrentIndex(index)">
          <mxp-icon-image
            v-if="item.icon"
            :icon="index === data.tabIndex ? item.activIcon || item.icon : item.icon"
            :size="item.iconSize || iconSize"
            :style="item.iconStyle"
            :cusStyle="imageStyle"
          ></mxp-icon-image>
          <text
            class="title vue"
            :style="{
              color: index === data.tabIndex ? item.activeColor || activeColor : item.color || color,
              fontSize: index === data.tabIndex ? item.fontSize || fontSize : item.fontSize || fontSize,
              fontWeight: bold && index === data.tabIndex ? 'bold' : 'normal',
              transform: `scale(${showZoomAnimation && index === data.tabIndex ? 1.1 : 1})`,
            }"
          >
            {{ item.label }}
          </text>
        </view>
        <mxp-line
          v-if="mode === 'subsection' && index !== newList.length - 1"
          direction="col"
          :hairline="false"
          :length="height"
          :color="themeColor"
        ></mxp-line>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
  import { publicStyeProps } from '../mxp-tool/utils/public-props';
  import { type CSSProperties, type PropType, computed, getCurrentInstance, onMounted, shallowReactive, watch } from 'vue';
  import type { $AllColorStr, $SizeUnitStr } from '@/mxp-ui/mxp-tool/types/interface';
  import { getDomSize, getXPNumber } from '../mxp-tool/utils/dom';
  import { getOnlyID } from '../mxp-tool/utils/common';
  import mxpIconImage from '../mxp-icon-image/mxp-icon-image.vue';
  import MxpLine from '../mxp-line/mxp-line.vue';
  export type $SubsectionItem = {
    [x: string]: unknown;
    /** 标题名称 */
    label: string;
    /** 图标 */
    icon?: string;
    /** 选中时图标 不传就显示未选中时的图标 */
    activIcon?: string;
    /** 图标大小 优先级高于在popup中设置的大小 */
    iconSize?: $SizeUnitStr;
    /** 角标 */
    badge?: number | string;
    /** 选中时的颜色 */
    activeColor?: $AllColorStr;
    /** 为选中的颜色 */
    color: $AllColorStr;
    /** 未选中时的颜色 */
    fontSize?: $AllColorStr;
  };
  defineOptions({
    name: 'mxp-subsection',
  });

  const props = defineProps({
    /** 当前的 index */
    current: { type: Number, default: 0 },
    /** 未选中时字体的颜色 */
    color: { type: String as PropType<$AllColorStr>, default: '#666666' },
    /** 模式  button | subsection */
    mode: { type: String as PropType<'button' | 'subsection'>, default: 'button' },
    /** 选中时字体的颜色 */
    activeColor: { type: String as PropType<$AllColorStr>, default: '#ffffff' },
    /** 主题色 */
    themeColor: { type: String as PropType<$AllColorStr>, default: '#6699f8' },
    /** 未选中时的字体大小 */
    fontSize: { type: String as PropType<$SizeUnitStr>, default: '14px' },
    /** 未选中时的字体是否加粗 */
    bold: { type: Boolean, default: true },
    /** 整个组件的背景 */
    background: { type: String as PropType<$AllColorStr>, default: undefined },
    /** 圆角 */
    borderRadius: { type: String as PropType<$SizeUnitStr>, default: ' 6px' },
    /** tab数组 [{  name: '全部', badge: 99 }] */
    list: { type: Array as PropType<($SubsectionItem | number | string)[]>, default: () => [] },
    /** 图标大小 优先级低于在list中设置的大小 */
    iconSize: { type: String as PropType<$SizeUnitStr>, default: '24px' },
    /** 图标的方向 */
    iconDirection: { type: String as PropType<'column' | 'row'>, default: 'column' },
    /** 整个组件的宽度 */
    width: { type: String as PropType<$SizeUnitStr>, default: undefined },
    /** 整个组件的高度 */
    height: { type: String as PropType<$SizeUnitStr>, default: '40px' },
    /** 文字是否显示缩放动画 */
    showZoomAnimation: { type: Boolean, default: false },
    /** 线条距离底部的距离 */
    lineBottom: { type: String as PropType<$SizeUnitStr>, default: '2px' },
    /** 整个 tabs 的样式 */
    tabsStyle: { type: Object as PropType<CSSProperties>, default: () => ({}) },
    /** 自定义选中后的样式 */
    activeStyle: { type: Object as PropType<CSSProperties>, default: () => ({}) },
    ...publicStyeProps,
  });

  const emits = defineEmits<{
    (e: 'update:current', vul: number): void;
    (e: 'change', vul: number): void;
  }>();

  const id = getOnlyID('mxp-subsection');
  const instance = getCurrentInstance();

  const data = shallowReactive({
    tabIndex: 0, // 导航栏被点击
    lineTranslateX: 0, // 导航栏下划线位置偏移
    itemWidth: 0, // 每个导航栏宽度
  });
  const subsectionStyle = computed<CSSProperties>(() => {
    const style: CSSProperties = { height: props.height, width: props.width, borderRadius: props.borderRadius, overflow: 'hidden' };
    if (props.mode === 'subsection') {
      style.border = `1px solid ${props.themeColor}`;
      style.background = props.background || '#ffffff';
    } else {
      style.background = props.background || '#f2F2F2';
    }
    return style;
  });
  const imageStyle = computed<CSSProperties>(() => {
    return props.iconDirection === 'row' ? { marginRight: '4px' } : { marginBottom: '4px' };
  });
  const buttonHeight = computed<$SizeUnitStr>(() => {
    return props.mode === 'button' ? `${getXPNumber(props.height, 40) * 0.7}px` : props.height;
  });
  const buttonWidth = computed<$SizeUnitStr>(() => {
    return props.mode === 'button' ? `${data.itemWidth * 0.8}px` : `${data.itemWidth}px`;
  });
  watch(
    () => props.current,
    (vul, old) => {
      if (vul !== old) {
        setCurrentIndex(vul);
      }
    }
  );
  watch(
    () => data.tabIndex,
    (vul, old) => {
      if (vul !== old) {
        emits('change', vul); // 设置swiper的第几页
      }
    }
  );

  const newList = computed<$SubsectionItem[]>(() => {
    return props.list.map((item) => {
      if (typeof item === 'number' || typeof item === 'string') {
        return { label: item, badge: '' } as $SubsectionItem;
      } else {
        return item;
      }
    });
  });

  onMounted(() => {
    setTimeout(() => {
      // 获取设备宽度
      getDomSize(`#${id}`, instance).then((rect) => {
        data.itemWidth = rect.width! / props.list.length; // 宽度除以导航标题个数=一个导航所占宽度
        data.tabIndex = props.current; // 设置导航点击了哪一个
        data.lineTranslateX = Math.round(props.current * data.itemWidth); // 设置下划线位置偏移
      });
    }, 10);
  });

  /** 设置导航点击了哪一个 */
  function setCurrentIndex(index: number) {
    data.tabIndex = index; // 设置导航点击了哪一个
    data.lineTranslateX = Math.round(index * data.itemWidth); // 设置下划线位置偏移
    emits('update:current', index);
  }

  defineExpose({
    /** 设置导航点击了哪一个 */
    setCurrentIndex,
  });
</script>

<style lang="scss" scoped>
  .mxp-subsection {
    position: relative;
    display: flex;
    flex-flow: column nowrap;
    align-items: flex-start;
    justify-content: center;

    .subsection-view {
      /* flex布局 等分居中 */
      position: absolute;
      z-index: 2;
      display: flex;
      flex-flow: row nowrap;
      align-items: center;
      justify-content: space-around;

      .subsection-item {
        /* flex布局 等分居中 */
        display: flex;
        flex: 1;
        flex-flow: row nowrap;
        align-items: center;
        justify-content: center;
        color: #666666;
        text-align: center;

        .title {
          font-size: 14px;
          transition-duration: 0.3s;
          transition-property: transform;

          .vue {
            // #ifndef APP-NVUE
            transition-duration: 0.3s;
            transition-property: color;
            // #endif
          }
        }
      }
    }

    .button-view {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      transition-duration: 0.3s;
      transition-property: transform;

      .button {
        background-color: #6699f8;
      }
    }
  }
</style>
